<?php

namespace common\modules\admin\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;
use common\components\Common;
/**
 * This is the model class for table "admins".
 *
 * @property integer $admin_id
 * @property string $username
 * @property string $name
 * @property string $idcard
 * @property string $phone
 * @propery  int    $position
 * @property string $password
 * @property string $salt
 * @property integer $deleted
 * @property string $_intm
 * @property integer $_uptm
 */
class Admin extends \common\components\ActiveRecord implements \yii\web\IdentityInterface
{

    /**
     * 删除状态1（删除）
     * @var int
     */
    const DELETED_YES = 1;
    /**
     * 删除状态0（未删除）
     * @var int
     */
    const DELETED_NO = 0;

    const SCENARIO_MODPWD = 'modpwd';
    const SCENARIO_SAVE = 'save';

    public $repassword;
    public static $dropdownFields = array(
        'deleted'=>array(self::DELETED_NO=>'正常',self::DELETED_YES=>'己删除'),
        'position' => [
            1 => '客响一线',
            2 => '客响主任',
            3 => '装维一线',
            4 => '装维经理',
            5 => '客户经理',
            6 => '政企接口',
            7 => '支撑一线',
            8 => '数据一线',
            20 => '支撑经理',
            21 => '数据经理',
            22 => '普通管理员',
            23 => '超级管理员',
        ],
    );
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admins';
    }

    public static function getDb(){
        return Yii::$app->get(Yii::$app->getModule('admin')->db);
    }

    public function behaviors(){
        return [[
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => '_intm',
            'updatedAtAttribute' => '_uptm',
        ]];
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['deleted', '_intm', '_uptm', 'position'], 'integer'],
            [['name', 'password', 'nick', 'phone',], 'required'],
            [['repassword'], 'required', 'on' => [self::SCENARIO_MODPWD]],
            [['phone'], 'string', 'max' => 11],
            [['phone'], 'unique'],
            [['username', 'nick', 'name'], 'string', 'max' => 20],
            [['password', 'repassword'], 'string', 'max' => 32],
            [['salt'], 'string', 'max' => 4],
            [['name'], 'unique'],
            [['repassword', 'password'], 'string', 'max' => 32, 'on' => [self::SCENARIO_MODPWD]],
            [['repassword'], 'pwdComplex', 'on' => [self::SCENARIO_MODPWD]],
            ['idcard', 'string', 'max' => 18],
        ];
    }

    /**
     * 校验密码复杂度
     * @param unknown $attribute
     * @param unknown $params
     */
    public function pwdComplex($attribute, $params){
        if (!$this->hasErrors()) {
            if (!Common::strongPassword($this->repassword)) {
                $this->addError('password', '密码中必须包含数字、大小写字母、特殊字符中的三种，且至少8位');
            }
        }
    }

    /**
     * 生成加密密码
     * @param string $password
     * @param string $salt
     * @return string
     */
    public static function generatePassword($password, $salt){
        return md5(md5($password).$salt);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'admin_id'  => '主键',
            'nick'      => '真实姓名',
            'name'  => '用户名',
            'password'  => '密码',
            'repassword'=> '确认密码',
            'salt'      => '随机码',
            'deleted'   => '是否删除',
            'idcard'    => '身份证',
            'phone'     => '手机号',
            'position'  => '岗位',
            '_intm'     => '创建时间',
            '_uptm'     => '更新时间',
            'assignment_role' => '授权角色',
            'username'  => '操作者'
        ];
    }

    public static function findIdentity($id) {
        return self::findOne(['admin_id'=>$id, 'deleted' => self::DELETED_NO]);
    }

    public static function findIdentityByAccessToken($token, $type = null) {
        return null;
    }

    public function getId() {
        return $this->admin_id;
    }

    public function getName(){
        return $this->name;
    }

    /**
     * (non-PHPdoc)
     * @see \yii\web\IdentityInterface::getAuthKey()
     */
    public function getAuthKey() {
        return md5($this->password.'_'.$this->salt);
    }

    public function validateAuthKey($authKey) {
        return $this->getAuthKey() == $authKey;
    }

    public function validatePassword($password)
    {
        return $this->password === md5(md5($password).$this->salt);
    }

    public static function dropDownList(){
        $init = ['0' => '请选择'];
        $dataList = self::find()->where(['deleted' => self::DELETED_NO])->all();
        if(!$dataList){
            return $init;
        }
        $dataList = ArrayHelper::map($dataList, 'id', 'name');
        return $init + $dataList;
    }

    public function getAssignment($admin_id){
        $assigement = Assignment::findOne(['user_id' => $admin_id]);
        if($assigement){
            return $assigement['item_name'];
        }else{
            return '';
        }
    }
}
